package com.test.model;

import java.io.*;
import java.util.List;

/**
 * Created by lms on 2017/11/17.
 */
public class Order implements Serializable, Cloneable {
    // 只有实现了Clonealbe接口，虚拟机才会认为clone是可用的，不然会抛出CloneNotSupportedException
    // 实现Serializable是为了可以进行流化clone，该clone为深clone
    // 原型模式分两步，第一步实现cloneable接口，第二步重写public 的 clone方法
    private String orderNo;

    private String orderName;

    private Integer money;

    private List<Goods> goods;

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }

    public List<Goods> getGoods() {
        return goods;
    }

    public void setGoods(List<Goods> goods) {
        this.goods = goods;
    }

    @Override
    public Order clone() throws CloneNotSupportedException {
//        //浅克隆 调用相同的堆地址
//        return (Order) super.clone();
//        //深clone，传统方式 非8基本类型或者String，需要通过new，然后为其copy值的方式来clone
//        Order myOrder = (Order) super.clone();
//
//        List<Goods> goods = new ArrayList<>();
//        for (Goods good : this.getGoods()) {
//            goods.add(good.clone());
//        }
//        myOrder.setGoods(goods);
//        return myOrder;

        // 深clone，流化方式，需要实现Serializable
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream;
        try {
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            // 写入流
            objectOutputStream.writeObject(this);

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream (
                    byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            // 读出流
            return (Order) objectInputStream.readObject();
        } catch (IOException e) {
            System.out.println("==IOException==");
        } catch (ClassNotFoundException e) {
            System.out.println("==ClassNotFoundException==");
        }
        return null;
    }
}
